from fastapi import FastAPI
import uvicorn
from functools import lru_cache
from pydantic import BaseModel

app = FastAPI(title="Fibonacci Sequence Service")


class FibonacciRequest(BaseModel):
    position: int
    use_cache: bool = True  # 是否使用缓存优化


# 记忆化装饰器优化递归计算
@lru_cache(maxsize=1000)
def cached_fib(n: int) -> int:
    if n <= 1:
        return n
    return cached_fib(n - 1) + cached_fib(n - 2)


# 普通递归计算（无优化）
def naive_fib(n: int) -> int:
    if n <= 1:
        return n
    return naive_fib(n - 1) + naive_fib(n - 2)


@app.post("/fibonacci")
async def calculate_fibonacci(request: FibonacciRequest):
    """计算斐波那契数列的指定位置数值"""
    if request.position < 0:
        return {"error": "位置必须是非负整数"}

    if request.use_cache:
        result = cached_fib(request.position)
    else:
        result = naive_fib(request.position)

    return {
        "position": request.position,
        "fibonacci_number": result,
        "calculation_method": "cached" if request.use_cache else "naive"
    }


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)